package prime

func sequence(max int) <-chan int {
	out:=make(chan int)

	go func(){
		for i:=2; i<=max; i++ {
			out <- i
		}
		close(out)
	}()

	return out
}

func filter(in <-chan int, prime int) <-chan int {
	out:=make(chan int)

	go func(){
		for v := range in {
			if v % prime != 0 {
				out <- v
			}
		}
		close(out)
	}()

	return out
}

func Generate(max int) <-chan int {
	out:=make(chan int)

	go func(){
		ch:=sequence(max)
		for {
			if prime, ok := <-ch; ok {
				ch=filter(ch, prime)
				out <- prime
			} else {
				close(out)
				break
			}
		}
	}()

	return out
}

